package com.up.stores.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.up.stores.entity.Collection;
import com.up.stores.mapper.CollectionMapper;
import com.up.stores.service.ICollectionService;
import com.up.stores.service.ex.ColletionInsertException;
import com.up.stores.service.ex.DeleteException;
import com.up.stores.service.ex.InsertException;
import com.up.stores.vo.CollectionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class CollectionImpl implements ICollectionService {
    @Autowired
    CollectionMapper collectionMapper;

    @Override
    public void addCollection(Integer uid, String type, Integer proId) {
        // 根据参数proId和uid查询收藏夹中的数据
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        if(type.equals("Admin")){
            queryWrapper.eq("adm_id", uid).eq("pro_id", proId);
        }else{
            queryWrapper.eq("nor_id", uid).eq("pro_id", proId);
        }
        Collection result = collectionMapper.selectOne(queryWrapper);
        // 判断查询结果是否为null
        //若某个物品已经加入该用户的收藏夹，则抛出提示该商品已加入收藏夹
        if (result == null) {
            // 是：表示该用户并未将该商品添加到购物车
            // 创建Collection对象
            Collection collection = new Collection();
            // 封装数据：uid, proId
            if(type.equals("Admin")) {collection.setAdmId(uid);}else{collection.setNorId(uid);}
            collection.setProId(proId);
            //此处与购物车不同，并没有将加入收藏夹时的商品价格，收藏夹中展示的是该商品的实时价格
            //调用insert(collection)执行将数据插入到数据表中
            Integer rows = collectionMapper.insert(collection);
            if (rows != 1) {
                throw new InsertException("插入商品数据时出现未知错误，请联系系统管理员");
            }
        } else {
            //这里抛异常是否合理？
                throw new ColletionInsertException("该商品已加入收藏夹");
        }
    }

    @Override
    public void deleteCollection(Integer colId) {
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("col_id", colId);
        Integer rows = collectionMapper.delete(queryWrapper);
        if (rows != 1) {
            throw new DeleteException("删除时出现未知错误");
        }
    }

    @Override
    public List<CollectionVO> getCollection(Integer uid, String type) {
        if(type.equals("Admin")){
            return collectionMapper.findCollectionVOByAdmId(uid);
        }else{
            return collectionMapper.findCollectionVOByNorId(uid);
        }
    }
}
